package daos

import (
	"goblog/pojo/entity"
	"goblog/tools"
)

type ArticleDao struct {
	*tools.Orm
}

func NewArticleDao(engine *tools.Orm) *ArticleDao {
	return &ArticleDao{
		engine,
	}
}

func (dao *ArticleDao)AddArticle(u *entity.Article)bool{
	_,err:=dao.InsertOne(u)
	if err!=nil{
		return false
	}
	return true
}

func (dao *ArticleDao)DelById(id int64)bool{
	blog := entity.Article{Id: id}
	if ok, _ := dao.Get(&blog); ok {
		_, err := dao.Id(id).Delete(blog)
		if err==nil {
			return true
		}
	}
	return false
}

func (dao *ArticleDao)UpdateArticle(article entity.Article)bool{
	_,err:=dao.Id(article.Id).Update(article)
	if err!=nil{
		return false
	}
	return true
}

func (dao *ArticleDao)GetArticleById(id int64) *entity.Article{
	var blog entity.Article
	blog = entity.Article{Id:id}
	_, err := dao.Get(&blog)
	if err!=nil{
		return nil
	}
	return &blog
}

func (dao *ArticleDao)GetArticlePage(start int,size int,article *entity.Article)([]entity.Article,int64){
	var articles []entity.Article
	whereStr := ""
	var tjStr []interface{}
	if article != nil {
		if len(article.Title) >0  {
			whereStr += "and title like ?"
			tjStr = append(tjStr,"%"+article.Title+"%" )
		}
		if len(article.UserName) >0  {
			whereStr += "and user_name like ?"
			tjStr = append(tjStr,"%"+article.UserName+"%" )
		}
		if article.ColumnId > 0  {
			whereStr += "and column_id = ?"
			tjStr = append(tjStr,article.ColumnId )
		}
		if len(article.Description) >0  {
			whereStr += "and description like ?"
			tjStr = append(tjStr, "%"+article.Description+"%")
		}
	}
	if len(whereStr)> 0{
		total,_ := dao.Where(whereStr,tjStr).Count()
		_ = dao.Where(whereStr,tjStr).Desc("create_time").Limit(size,start).Find(&articles)
		return articles,total
	}else{
		total,_ := dao.Count()
		_ = dao.Desc("create_time").Limit(size,start).Find(&articles)
		return articles,total
	}
}

func (dao *ArticleDao) FindTop(size int) []entity.Article {
	var articles []entity.Article
	err := dao.Desc("visit_num").Limit(size,0).Find(&articles)
	if err != nil {
		return nil
	}
	return articles
}

func (dao *ArticleDao) FindAuthorTop(userId int64, size int) []entity.Article {
	var article entity.Article
	article = entity.Article{UserId:userId}

	var articles []entity.Article
	err := dao.Desc("visit_num").Limit(size,0).Find(&articles,article)
	if err != nil {
		return nil
	}
	return articles
}
